<template>
  <form @submit.prevent="submit" class="space-y-6">
    <!-- 基本信息 -->
    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
      <div>
        <label for="name" class="block text-sm font-medium text-gray-700">
          收货人姓名 <span class="text-red-500">*</span>
        </label>
        <input 
          type="text" 
          id="name" 
          v-model="form.name" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm" 
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.name }"
          required
        />
        <p v-if="form.errors.name" class="mt-1 text-sm text-red-600">{{ form.errors.name }}</p>
      </div>

      <div>
        <label for="phone" class="block text-sm font-medium text-gray-700">
          手机号 <span class="text-red-500">*</span>
        </label>
        <input 
          type="tel" 
          id="phone" 
          v-model="form.phone" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm" 
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.phone }"
          required
        />
        <p v-if="form.errors.phone" class="mt-1 text-sm text-red-600">{{ form.errors.phone }}</p>
      </div>
    </div>

    <!-- 地址选择 -->
    <div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
      <div>
        <label for="province" class="block text-sm font-medium text-gray-700">
          省份 <span class="text-red-500">*</span>
        </label>
        <select 
          id="province" 
          v-model="form.province" 
          @change="onProvinceChange" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm"
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.province }"
          required
        >
          <option value="">请选择省份</option>
          <option v-for="province in provinces" :key="province.id" :value="province.id">
            {{ province.name }}
          </option>
        </select>
        <p v-if="form.errors.province" class="mt-1 text-sm text-red-600">{{ form.errors.province }}</p>
      </div>

      <div>
        <label for="city" class="block text-sm font-medium text-gray-700">
          城市 <span class="text-red-500">*</span>
        </label>
        <select 
          id="city" 
          v-model="form.city" 
          @change="onCityChange" 
          :disabled="!form.province || cities.length === 0" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.city }"
          required
        >
          <option value="">{{ cities.length === 0 ? '请先选择省份' : '请选择城市' }}</option>
          <option v-for="city in cities" :key="city.id" :value="city.id">
            {{ city.name }}
          </option>
        </select>
        <p v-if="form.errors.city" class="mt-1 text-sm text-red-600">{{ form.errors.city }}</p>
      </div>

      <div>
        <label for="district" class="block text-sm font-medium text-gray-700">
          区/县 <span class="text-red-500">*</span>
        </label>
        <select 
          id="district" 
          v-model="form.district" 
          :disabled="!form.city || districts.length === 0" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm disabled:bg-gray-50 disabled:text-gray-500"
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.district }"
          required
        >
          <option value="">{{ districts.length === 0 ? '请先选择城市' : '请选择区/县' }}</option>
          <option v-for="district in districts" :key="district.id" :value="district.id">
            {{ district.name }}
          </option>
        </select>
        <p v-if="form.errors.district" class="mt-1 text-sm text-red-600">{{ form.errors.district }}</p>
      </div>
    </div>

    <!-- 详细地址 -->
    <div>
      <label for="address" class="block text-sm font-medium text-gray-700">
        详细地址 <span class="text-red-500">*</span>
      </label>
      <textarea 
        id="address" 
        v-model="form.address" 
        rows="3" 
        class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm"
        :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.address }"
        placeholder="请输入街道、门牌号等详细信息"
        required
      ></textarea>
      <p v-if="form.errors.address" class="mt-1 text-sm text-red-600">{{ form.errors.address }}</p>
    </div>

    <!-- 可选信息 -->
    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
      <div>
        <label for="postal_code" class="block text-sm font-medium text-gray-700">邮政编码</label>
        <input 
          type="text" 
          id="postal_code" 
          v-model="form.postal_code" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm"
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.postal_code }"
          placeholder="可选"
        />
        <p v-if="form.errors.postal_code" class="mt-1 text-sm text-red-600">{{ form.errors.postal_code }}</p>
      </div>

      <div>
        <label for="label" class="block text-sm font-medium text-gray-700">地址标签</label>
        <input 
          type="text" 
          id="label" 
          v-model="form.label" 
          placeholder="例如：家、公司、学校" 
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-gray-900 focus:ring-gray-900 sm:text-sm"
          :class="{ 'border-red-300 focus:border-red-500 focus:ring-red-500': form.errors.label }"
        />
        <p v-if="form.errors.label" class="mt-1 text-sm text-red-600">{{ form.errors.label }}</p>
      </div>
    </div>

    <!-- 默认地址选项 -->
    <div class="flex items-center">
      <input 
        type="checkbox" 
        id="is_default" 
        v-model="form.is_default" 
        class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900"
      />
      <label for="is_default" class="ml-2 block text-sm text-gray-700">
        设为默认地址
      </label>
    </div>

    <!-- 操作按钮 -->
    <div class="flex justify-end gap-3 pt-4 border-t border-gray-200">
      <button
        type="button"
        @click="emit('cancel')"
        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
      >
        取消
      </button>
      <button
        type="submit"
        :disabled="form.processing"
        class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-gray-900 border border-transparent rounded-md shadow-sm hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <svg v-if="form.processing" class="w-4 h-4 mr-2 animate-spin" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        {{ form.processing ? '保存中...' : '保存地址' }}
      </button>
    </div>
  </form>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useForm, router } from '@inertiajs/vue3'
import { useNotification } from '@/composables/useNotification'

// 定义组件选项
defineOptions({
  name: 'AddressForm',
  inheritAttrs: false
})

// 定义 Props 和 Emits
const props = defineProps({
  address: {
    type: Object,
    default: null
  },
  provinces: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['cancel', 'address-saved'])

const { showSuccess, showError } = useNotification()

// 使用 Inertia.js 的 useForm
const form = useForm({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  postal_code: '',
  label: '',
  is_default: false
})

// 地址数据
const cities = ref([])
const districts = ref([])

// 使用服务器端传递的省份数据
const provinces = computed(() => props.provinces || [])

// 加载城市数据
const loadCities = async (provinceId) => {
  try {
    const response = await fetch(route('api.cities', { province_id: provinceId }), {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    if (data.success && data.data) {
      cities.value = data.data
    } else {
      throw new Error('Invalid response format')
    }
  } catch (error) {
    console.error('加载城市失败:', error)
    showError('加载失败', '无法加载城市数据，请重试')
  }
}

// 加载区县数据
const loadDistricts = async (cityId) => {
  try {
    const response = await fetch(route('api.districts', { city_id: cityId }), {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    if (data.success && data.data) {
      districts.value = data.data
    } else {
      throw new Error('Invalid response format')
    }
  } catch (error) {
    console.error('加载区县失败:', error)
    showError('加载失败', '无法加载区县数据，请重试')
  }
}

// 省份变化处理
const onProvinceChange = async () => {
  form.city = ''
  form.district = ''
  cities.value = []
  districts.value = []
  
  if (form.province) {
    await loadCities(form.province)
  }
}

// 城市变化处理
const onCityChange = async () => {
  form.district = ''
  districts.value = []
  
  if (form.city) {
    await loadDistricts(form.city)
  }
}

// 提交表单
const submit = () => {
  // 获取选中的省市区名称
  const selectedProvince = provinces.value.find(p => p.id == form.province)
  const selectedCity = cities.value.find(c => c.id == form.city)
  const selectedDistrict = districts.value.find(d => d.id == form.district)

  // 准备提交数据（保存字符串格式的省市区名称）
  const submitData = {
    name: form.name,
    phone: form.phone,
    province: selectedProvince?.name || '',
    city: selectedCity?.name || '',
    district: selectedDistrict?.name || '',
    address: form.address,
    postal_code: form.postal_code,
    label: form.label,
    is_default: form.is_default
  }

  const url = props.address
    ? route('addresses.update', props.address.id)
    : route('addresses.store')
  const method = props.address ? 'put' : 'post'

  // 使用router提交数据
  router[method](url, submitData, {
    onSuccess: () => {
      emit('address-saved')
      // 不在这里显示通知，由父组件处理
    },
    onError: (errors) => {
      const firstError = Object.values(errors)[0]
      showError('保存地址失败', Array.isArray(firstError) ? firstError[0] : firstError)
    }
  })
}

// 初始化表单数据
const initializeForm = () => {
  if (props.address) {
    form.name = props.address.name || ''
    form.phone = props.address.phone || ''
    // 查找对应的省份ID（用于下拉选择）
    const provinceObj = provinces.value.find(p => p.name === props.address.province)
    form.province = provinceObj ? provinceObj.id : ''
    form.city = ''
    form.district = ''
    form.address = props.address.address || ''
    form.postal_code = props.address.postal_code || ''
    form.label = props.address.label || ''
    form.is_default = props.address.is_default || false
  } else {
    form.reset()
  }
}

// 监听地址变化
watch(() => props.address, async (newAddress) => {
  initializeForm()
  
  if (form.province) {
    await loadCities(form.province)
    // 查找对应的城市ID
    if (newAddress && newAddress.city) {
      const cityObj = cities.value.find(c => c.name === newAddress.city)
      if (cityObj) {
        form.city = cityObj.id
        await loadDistricts(form.city)
        // 查找对应的区县ID
        if (newAddress.district) {
          const districtObj = districts.value.find(d => d.name === newAddress.district)
          if (districtObj) {
            form.district = districtObj.id
          }
        }
      }
    }
  }
}, { immediate: true })

// 组件挂载时初始化表单
onMounted(() => {
  initializeForm()
})
</script>